package com.fx.controller;

import com.fx.common.RootStage;
import com.fx.server.FxUiAuthServer;
import com.fx.view.MainStageView;
import de.felixroske.jfxsupport.FXMLController;
import javafx.event.Event;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseEvent;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.ByteArrayInputStream;
import java.net.URL;
import java.util.ResourceBundle;

@FXMLController
public class LoginController implements Initializable {

    @FXML
    private ImageView imageCode;

    @Autowired
    private MainStageView mainStageView;

    @Autowired
    private FxUiAuthServer fxUiAuthServer;

    private void loadImageCode(){
        ByteArrayInputStream inputStream
                = fxUiAuthServer.currentBase64ImageCode();

        Image image = new Image(inputStream);
        imageCode.setImage(image);

        imageCode.setOnMouseClicked(new EventHandler<MouseEvent>() {
            @Override
            public void handle(MouseEvent event) {
                ByteArrayInputStream input
                        = fxUiAuthServer.currentBase64ImageCode();
                Image img = new Image(input);
                imageCode.setImage(img);
            }
        });
    }

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        loadImageCode();
    }

    public void loginAction(final Event e){
        // 组件登录判断
        final Stage stage = new Stage(StageStyle.DECORATED);
        stage.setMaximized(true);
        final Scene scene = new Scene(mainStageView.getView(), Color.TRANSPARENT);
        stage.setScene(scene);
        RootStage.saveRoot(stage);
        stage.show();
        //stage.getIcons().add(null);
        ((Node)e.getSource()).getScene().getWindow().hide();
    }

}
